<?php

namespace App\Repositories;

use App\Interfaces\UserPointLogService;
use App\Models\UserPoint;

class UserPointLogRepository implements UserPointLogService{

    /**
     *
     * 增加或减少积分
     *
     * @param $user_id          要加或减积分的用户id
     * @param $reson            原因
     * @param $userPointNum     要加或减积分
     * @param $isAdd            判断是加还是减  true 加| false 减
     * @return mixed            写入数据是否成功  boolean
     */
    public function add($user_id, $reason, $userPointNum, $isAdd)
    {
        $oldUserPoint = UserPoint::where('user_id',$user_id)->orderBy('update_time', 'desc')->first();

        if(empty($oldUserPoint)) {
            $oldPointNum = 0;
        } else {
            $oldPointNum = $oldUserPoint->number;
        }

        $userPointLog = new UserPoint;
        $userPointLog->user_id = $user_id;
        $userPointLog->reason = $reason;
        $userPointLog->type = $isAdd;
        $userPointLog->update_time =  date("Y-m-d h:i:s");

        if($isAdd)
            $userPointLog->number = $oldPointNum + $userPointNum;
        else
            $userPointLog->number = $oldPointNum - $userPointNum;

        return $userPointLog->save();

    }

    /**
     *
     * 仅仅获取user的积分
     *
     * @param $user_id              用户id
     * @return mixed                用户积分
     */
    public function getPoint($user_id)
    {

        $oldPointLog = UserPoint::where('user_id', $user_id)->orderBy('update_time', 'desc')->first();
        if (empty($oldPointLog)) {
            $oldPointNum = 0;
        } else {
            $oldPointNum = $oldPointLog->number;
        }
        return $oldPointNum;
    }


    /**
     *
     *  获取该用户的所有积分信息
     *
     * @param $user_id              用户id
     * @return mixed                UserPointLogModel
     */
    public function getPointLog($user_id)
    {

        $userPointLog = UserPoint::where('user_id', $user_id)->orderBy('update_time', 'desc')->paginate(20);

        return $userPointLog;

    }

    /**
     *
     * 删除用户的积分日志
     *
     * @param $user_id
     * @return mixed
     */
    public function deletePoint($user_id) {
        UserPoint::where('user_id', '=', $user_id)->delete();
    }
}